package com.tanhua.sso.service;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;

@Service
public class SmsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public ErrorResult sendCheckCode(String phone) {

        //根据手机号获取user
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", phone);
        User user = userMapper.selectOne(queryWrapper);

        if (user != null) {
            //根据userId检验是否存在冻结
            String key = "USER_FREEZE_RANGE_" + user.getId();
            String freezeRange = redisTemplate.opsForValue().get(key);
            if (ObjectUtil.isNotEmpty(freezeRange) && freezeRange.equals("1")) {
                return null;
                //return ErrorResult.builder().errCode("100").errMessage("你的账号已被冻结！").build();
            }
        }

        String codeKey = "CHECK_CODE_" + phone;

        //判断是否有key所对应的值，有则返回true，没有则返回false
        Boolean flag = redisTemplate.hasKey(codeKey);
        if (flag) {
            return ErrorResult.builder().errCode("101").errMessage("验证码的效果还存在").build();
        }
        String code = "123456";
        redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(5));
        return null;
    }
}
